package com.M10.BE;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.fn.useries.model.ResponseHandler;
import com.fn.useries.operation.U8Series;
import com.fn.useries.reader.model.InventoryBuffer;
import com.fn.useries.reader.server.ReaderHelper;
import com.hsm.barcode.DecoderException;
import com.hsm.barcode.ExposureValues.ExposureMode;
import com.hsm.barcode.ExposureValues.ExposureSettings;

import java.util.List;

public class MainActivity extends Activity implements OnClickListener {
    private static final String TAG = BEutils.TAG;
    public static MainActivity instance = null;
    private static int g_ScanKey = BEutils.g_ScanKey;
    private static final int SCAN_KEY = BEutils.SCAN_KEY;//-1;		// Scan key default
    //
    public static Button bt_start, bt_stop, bt_clear, bt_codeSelect, bt_scanModel, bt_scanInterval, bt_exit, bt_encoding, btn_u8;
    private final CharSequence[] codes = {"ASCII", "GB2312", "UTF8", "Unicode"};
    private final CharSequence[] models = {"单次扫描", "连续扫描"};
    private final CharSequence[] interval = {"1s", "2s", "3s"};
    //
    private int codeSelected = 0;
    private int modelSelected = 0;
    private int intervalSelected = 0;
    private AlertDialog alert;

    private final String codeKey = "codeSelected";
    private final String modelKey = "modelSelected";
    private final String intervalKey = "intervalSelected";
    private String model = "U8";
    private static InventoryBuffer m_curInventoryBuffer = null;


    private boolean isDecodeAlways = false;

    private int scan_interval = 1;

    private int much = 1; //1 单次扫描  2 多次扫描 3停止扫描
    private int time = 0; // 1000 1s 2000 2s 3000 3s

    private U8Series mUSeries;
    private ReaderHelper mReaderHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //M10A_GPIO.BdPowerOn();
        //
        instance = this;
        g_ScanKey = SCAN_KEY;
        Log.d(TAG, "g_ScanKey=" + g_ScanKey);
        if (g_ScanKey == -1) // not initialized
        {
            Log.d(TAG, "Please define SCAN_KEY");
        }
        init();
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());

        mUSeries = U8Series.getInstance();
        U8Series.setContext(this);

        com.fn.useries.model.Message openSerialPortMeaasge = mUSeries.openSerialPort(model);
        if (openSerialPortMeaasge.getCode() != 0) {
            Log.e(TAG, "bt_u8 -----openSerialPortMeaasge: " + "/**\n" +
                    "\t * 若配置文件丟失,跳转到配置工具\n" +
                    "\t */");
            return;
        }
        try {
            m_curInventoryBuffer = ReaderHelper.getDefaultHelper().getCurInventoryBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void init() {
        bt_start = (Button) findViewById(R.id.bt_start);
        bt_start.setOnClickListener(this);
        bt_stop = (Button) findViewById(R.id.bt_stop);
        bt_stop.setOnClickListener(this);
        bt_stop.setEnabled(false);
        bt_clear = (Button) findViewById(R.id.bt_clear);
        bt_clear.setOnClickListener(this);
        bt_clear.setEnabled(false);
        int a = R.string.success;
        //
        bt_codeSelect = (Button) findViewById(R.id.bt_codeSelect);
        bt_scanModel = (Button) findViewById(R.id.bt_scanModel);
        bt_scanInterval = (Button) findViewById(R.id.bt_scanInterval);
        bt_encoding = (Button) findViewById(R.id.bt_encoding);
        //
        bt_codeSelect.setOnClickListener(this);
        bt_scanModel.setOnClickListener(this);
        bt_scanInterval.setOnClickListener(this);
        bt_encoding.setOnClickListener(this);
        //
        bt_exit = (Button) findViewById(R.id.bt_exit);
        bt_exit.setOnClickListener(this);

        btn_u8 = (Button) findViewById(R.id.bt_u8);
        btn_u8.setOnClickListener(this);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    bt_start.setEnabled(false);
                    bt_stop.setEnabled(true);
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.bt_start) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (much == 1) {
                        BEutils.Scanning();
                    }
                    if (much == 2) {
                        Message message = new Message();
                        int what = message.what = 1;
                        handler.sendEmptyMessage(what);
                        while (true) {
                            try {
                                Thread.sleep(time);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            BEutils.Scanning();
                            if (much == 3) {
                                much = 2;
                                break;
                            }
                        }
                    }
                }
            }).start();
        }
        if (id == R.id.bt_stop) {
            much = 3;
            bt_start.setEnabled(true);
            bt_stop.setEnabled(false);
            BEutils.stopScaning();
        }
        if (id == R.id.bt_clear) {
//            BEutils.m_DecodeResultsView.setText("");
        }
        if (id == R.id.bt_codeSelect) {
            myShowDialog(this.getApplicationContext().getString(R.string.codeSelect), codes, codeSelected, codeKey);
        }
        if (id == R.id.bt_scanModel) {
            myShowDialog(this.getApplicationContext().getString(R.string.scanModel), models, modelSelected, modelKey);
        }
        if (id == R.id.bt_scanInterval) {
            myShowDialog(this.getApplicationContext().getString(R.string.scanInterval), interval, intervalSelected, intervalKey);
        }
        if (id == R.id.bt_encoding) {
            myShowDialog(this.getApplicationContext().getString(R.string.codeSelect), codes, codeSelected, codeKey);
        }
        if (id == R.id.bt_exit) {
            finish();
            //android.os.Process.killProcess(android.os.Process.myPid());
        }
        if (id == R.id.bt_u8) {



            Log.e("U8", "开始按键被按下");
//            isInventory = true;
            try {
////                mRefreshTime = new Date().getTime();
//                U8Series.setContext(MainActivity.this);
                mUSeries = U8Series.getInstance();

                mUSeries.startInventory(new ResponseHandler() {

                    @Override
                    public void onFailure(String msg) {
                        super.onFailure(msg);
                        Log.e("U8", msg);
                        Toast.makeText(MainActivity.this, getResources().getText(R.string.Disk_failure) + msg, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(String msg, Object data, byte[] parameters) {
                        super.onSuccess(msg, data, parameters);
                        if (msg.equals(U8Series.REFRESHTEXT)) {
//                            refreshText();
                            Log.e(TAG, "refreshText: " + msg);
                        } else if (msg.equals(U8Series.REFRESHLIST)) {
                            List<InventoryBuffer.InventoryTagMap> tagMapList =
                                    (List<InventoryBuffer.InventoryTagMap>) data;
                            for (int i = 0; i < tagMapList.size(); i++) {
                                Log.e("list",i+">>>>>>" +tagMapList.get(i).strEPC+"-------"+tagMapList.get(i).strCRC);
                            }
//                            inventoryTagData.clear();
//                            inventoryTagData.addAll((Collection<? extends InventoryBuffer.InventoryTagMap>) data);
//                            inventoryAdapter.notifyDataSetChanged();
                        } else {
                            Log.e("U8", "盘询成功,返回标识异常");
//                            System.out.println("盘询成功,返回标识异常");
                        }
                    }

                });
//                mHandler.postDelayed(mRefreshRunnable, 500);
//                btnStart.setEnabled(false);
//                btnStop.setEnabled(true);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("Exception", "盘询成功,返回标识异常");
            }

//            Toast.makeText(MainActivity.this, "待接入rfid接口", Toast.LENGTH_SHORT).show();
        }
    }

    private void myShowDialog(final String titleName,
                              final CharSequence[] items, int selected, final String key) {
        // int saved = sp.getInt(key, selected);
        int saved = selected;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(titleName);
        builder.setSingleChoiceItems(items, saved,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {

                        Toast.makeText(getApplicationContext(), items[item],
                                Toast.LENGTH_SHORT).show();
                        if (items[item].equals("单次扫描")) {
                            much = 1;
                        }
                        if (items[item].equals("连续扫描")) {
                            much = 2;
                        }
                        if (items[item].equals("1s")) {
                            time = 1000;
                        }
                        if (items[item].equals("2s")) {
                            time = 2000;
                        }
                        if (items[item].equals("3s")) {
                            time = 3000;
                        }
                        alert.dismiss();
                    }
                });

        alert = builder.create();
        alert.show();
    }

    //    /**
//	  * Called when key is down 当键被按下时调用
//	  *
//	  */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d(TAG, "onKeyDown" + "keyCode=" + keyCode + "(g_ScanKey=" + g_ScanKey + ")");

        if (keyCode == g_ScanKey) {

            BEutils.Scanning();
        } else {
            return super.onKeyDown(keyCode, event);
        }

        return false;
    }

    /**
     * Called when key is up 当键被松开时调用
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        Log.d(TAG, "onKeyUp" + "keyCode=" + keyCode + "(g_ScanKey=" + g_ScanKey + ")");

        if (keyCode == g_ScanKey) {
            if (!BEutils.g_bContinuousScanEnabled) {
                BEutils.StopScanning();
            }
        } else {
            return super.onKeyUp(keyCode, event);
        }

        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        com.fn.useries.model.Message powerOnMessage = mUSeries.modulePowerOn(model);
        if (powerOnMessage.getCode() != 0) {
            Log.e(TAG, "onResume: " + "/**\n" +
                    "\t * 若配置文件丟失,跳转到配置工具\n" +
                    "\t */");
        }


        BEutils.Decoder();
        new Thread(new BEutils.Task()).start();
        BEutils.bRunThread = true;

        int g_nExposureSettings[] =

                {
                        ExposureSettings.DEC_ES_MAX_EXP, 130,
                };

        try {
            BEutils.m_Decoder.setExposureSettings(g_nExposureSettings);
            BEutils.m_Decoder.setExposureMode(ExposureMode.HHP);
        } catch (DecoderException e) {
            BEutils.HandleDecoderException(e);
        }


        if (!BEutils.bAppRetainsPreferences) {
            BEutils.bAppRetainsPreferences = true;

            // Configure preference settings to defaults...
            Log.d(TAG, "Configure preference settings to defaults...");

            BEutils.SetSymbologyPreferences(true);
            BEutils.SetOcrPreferences(true);
            BEutils.SetDecodingPreferences(true);
            BEutils.SetScanningPreferences(true);
            BEutils.SetApplicationPreferences(true);
        }

        // Re-configure preferences based on user preferences...
        Log.d(TAG, "Configure preferences based on user settings...");
        try {
            //BEutils.SetSymbologySettings();
            BEutils.SetOcrSettings();
            BEutils.SetDecodingSettings();
            BEutils.SetScanningSettings();
            BEutils.SetApplicationSettings();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        BEutils.Pause();

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * Called when the user clicks the save button
     */
    public void onClickSaveImage(View view) {
        //Log. d(TAG, "onClickSaveImage++");

        BEutils.saveLastImage();

        //Log. d(TAG, "onClickSaveImage--");
    }

}
